package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author Mr_Su
 * @since 2022-06-26
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        // 1.判断是否缺少参数
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2.根据用户名查询用户是否存在
        LambdaQueryWrapper<AdUser> lqwAdUser = new LambdaQueryWrapper<>();
        lqwAdUser.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(lqwAdUser);

        if (one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AD_User_NOT_EXIST);
        }
        // 3.比较密码
        // 将明文加盐后再通过md5加密,与表中数据进行比较
        String password_enc = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());

        if (!one.getPassword().equals(password_enc)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 4.返回前端需要的数据
        Map resultMap = new HashMap();
        // 去除用户one中的敏感数据
        one.setPassword("");
        one.setPhone("");
        one.setSalt("");
        one.setEmail("");
        resultMap.put("user",one);

        Map claimMaps = new HashMap();
        claimMaps.put("userId",one.getId());
        claimMaps.put("name",one.getName());
        String token = AppJwtUtil.getToken(claimMaps);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
